package com.ykt.weixin;

import java.io.StringReader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

import com.jfinal.ext.route.ControllerBind;
import com.ykt.common.pay.wx.RefundUtil;
import com.ykt.controller.BaseController;
import com.ykt.model.Order;

/**
 * 微信其它操作，如退款
 *
 * @author wing
 * @version 1.0.0
 */
@ControllerBind(controllerKey="/wx")
public class WxController extends BaseController<Order> {

	private final  static Logger log = LoggerFactory.getLogger(WxController.class);
	
	public WxController() {
		super(Order.class);
	}
	
	/**
	 * 退款
	 */
    public void refund(){
    	int orderId = getParaToInt(0);
    	double refundFee = !isParaExists(1) ? 0.0 : Double.valueOf(getPara(1));
    	
    	String msg = "退款成功！";
		try {
			Order o = Order.dao.findById(orderId);
			String orderNo = "";
	    	if(o.getStr("order_type").equals("SINGLE")){
	    		orderNo = o.getStr("order_no");
	    	}else if(o.getStr("order_type").equals("SON")){
	    		orderNo = o.getStr("order_pno");
	    	}
	    	
	    	double payAmount = o.getBigDecimal("pay_amount").doubleValue();
	    	double agentFee = o.getBigDecimal("agent_fee").doubleValue();
	    	double totalFee = payAmount - agentFee;
	    	if(refundFee == 0.0){
	    		refundFee = totalFee;
	    	}
			String resultCode = "SUCCESS";
			
	    	if(!orderNo.equals("")){
	    		String refundResult = RefundUtil.wechatPartialRefund(orderNo, totalFee, refundFee);
	    		Map m = parseXmlToList(refundResult);
	    		
	    		resultCode = m.get("result_code").toString();
	    		
	    		if(resultCode.equals("SUCCESS")){
		    		o.set("status", "MERCHANT_RETURN");
		    		o.set("updated_time", new Date());
		    		o.update();
		    	}else{
		    		msg = m.get("err_code_des").toString();
		    	}
	    	}
	    	
			
			int id = o.getInt("id");
			rendJson(true, msg, id, new Random().nextLong());
		} catch (Exception e) {
			log.error("保存异常", e);
			rendJson(false, "保存异常！");
			e.printStackTrace();
		}
    }
    
    private static Map parseXmlToList(String xml) {
		Map retMap = new HashMap();
		try {
			StringReader read = new StringReader(xml);
			// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			// 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			// 通过输入源构造一个Document
			Document doc = (Document) sb.build(source);
			Element root = doc.getRootElement();// 指向根节点
			List<Element> es = root.getChildren();
			if (es != null && es.size() != 0) {
				for (Element element : es) {
					retMap.put(element.getName(), element.getValue());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;
	}
    
}
